package com.example.uniapp.activity.userHome;
/**
 * 添加食谱界面
 */

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import com.example.uniapp.R;
import com.example.uniapp.activity.main.MainUserActivity;
import com.example.uniapp.dao.CookbookDao;
import com.example.uniapp.dao.CookbookFoodDao;
import com.example.uniapp.dao.CookbookStepDao;
import com.example.uniapp.utils.FileImgUtils;
import com.example.uniapp.utils.Tools;

import java.util.ArrayList;
import java.util.List;

public class UserAddCookbookActivity extends AppCompatActivity {
    private ActivityResultLauncher<String> getContentLaucher;
    private Uri uri;
    private LinearLayout foodInputLayout;
    private LinearLayout cookbookStepInputLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_add_cookbook);

        Toolbar toolbar = findViewById(R.id.user_bottom_menu_add_cookbook_toolbar);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(UserAddCookbookActivity.this, MainUserActivity.class);
                startActivity(intent);
            }
        });

        //获取界面中的各个组件
        foodInputLayout = findViewById(R.id.user_bottom_menu_add_cookbook_food);
        cookbookStepInputLayout = findViewById(R.id.user_bottom_menu_add_cookbook_step);
        ImageView imgView = findViewById(R.id.user_bottom_menu_add_cookbook_img);
        EditText nameText = findViewById(R.id.user_bottom_menu_add_cookbook_name);

        //初始化第一个输入框
        addFoodInputItem();
        addStepInputItem();

        //获取用户名
        String userId = Tools.getOnAccount(this);

        //初始化文件选择器
        getContentLaucher=registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                if(result!=null) {
                    imgView.setImageURI(result);
                    uri=result;
                }else {
                    Toast.makeText(UserAddCookbookActivity.this, "未选择食品图片", Toast.LENGTH_SHORT).show();
                }
            }
        });

        imgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openGallery(view);
            }
        });

        //当点击按钮时的操作
        Button addCookbookButton = findViewById(R.id.user_bottom_menu_add_cookbook_add_button);
        addCookbookButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //提取各属性
                String name = nameText.getText().toString();

                //判断各属性是否都输入了
                if(name.isEmpty()) {
                    Toast.makeText(UserAddCookbookActivity.this, "请添加食品名", Toast.LENGTH_SHORT).show();
                }else {
                    //获取默认图片
                    Drawable defaultDrawable = ContextCompat.getDrawable(UserAddCookbookActivity.this, R.drawable.default_avator);
                    Drawable imgDrawable = imgView.getDrawable(); //获取图片
                    Bitmap imgBitmap = ((BitmapDrawable) imgDrawable).getBitmap();
                    Bitmap defaultBitmap = ((BitmapDrawable) defaultDrawable).getBitmap();

                    //判断是否有添加食品图片
                    if (imgBitmap.sameAs(defaultBitmap)) {
                        //如果二者相等，代表未添加食品图片
                        Toast.makeText(UserAddCookbookActivity.this, "请点击图片以添加食品图片", Toast.LENGTH_SHORT).show();
                    }else {
                        //判断所有的食材输入框是否有输入
                        Boolean foodMark = true;
                        List<String> foodNames = new ArrayList<>();
                        List<String> foodCounts = new ArrayList<>();
                        for(int i = 0; i < foodInputLayout.getChildCount(); i++) {
                            View itemView = foodInputLayout.getChildAt(i);
                            EditText foodNameEditText = itemView.findViewById(R.id.itemview_food_input_layout_food_name);
                            EditText foodCountEditText = itemView.findViewById(R.id.itemview_food_input_layout_food_count);

                            String foodName = foodNameEditText.getText().toString().trim();
                            String foodCount = foodCountEditText.getText().toString().trim();
                            Log.d("foodName", foodName);
                            Log.d("foodCount", foodCount);

                            if(foodName.isEmpty() || foodCount.isEmpty()) {
                                Toast.makeText(UserAddCookbookActivity.this, "有食材信息未输入", Toast.LENGTH_SHORT).show();
                                foodMark = false;
                            }else {
                                foodNames.add(foodName);
                                foodCounts.add(foodCount);
                            }
                        }

                        //判断所有的步骤输入框是否有输入
                        Boolean stepMark = true;
                        List<String> steps = new ArrayList<>();
                        for(int i = 0; i < cookbookStepInputLayout.getChildCount(); i++) {
                            View itemView = cookbookStepInputLayout.getChildAt(i);

                            EditText stepEditText = itemView.findViewById(R.id.itemview_step_input_layout_step);
                            String step = stepEditText.getText().toString().trim();

                            if(step.isEmpty()) {
                                Toast.makeText(UserAddCookbookActivity.this, "有制作食谱步骤信息未输入", Toast.LENGTH_SHORT).show();
                                stepMark = false;
                            }else {
                                steps.add(step);
                            }
                        }

                        if(foodMark && stepMark) {
                            //运行到这，代表可以保存数据到数据库
                            String imgPath = FileImgUtils.getImgName(); //获取图片存储路径
                            FileImgUtils.saveImageUriToFileImg(uri, UserAddCookbookActivity.this, imgPath); //保存图片

                            //存入数据库
                            int cookbookResult = CookbookDao.addCookbook(userId, name, imgPath);

                            //获取食谱id，然后存食谱信息
                            int cookbookFoodResult = 0;
                            int cookbookStepResult = 0;
                            String cookbookId = CookbookDao.getCookbookId(name, userId);
                            for(int i = 0; i < foodNames.size(); i++) {
                                String foodName = foodNames.get(i);
                                String foodCount = foodCounts.get(i);

                                //插入食谱食材信息
                                cookbookFoodResult = CookbookFoodDao.addCookbookFood(cookbookId, foodName, foodCount);
                                if(cookbookFoodResult == 0) {
                                    for(int j = 0; j < i; j++) {
                                        //如果插入失败，那么之前插入的要删除
                                        CookbookFoodDao.deleteCookbookFood(cookbookId);
                                    }
                                    CookbookFoodDao.deleteCookbookFood(cookbookId);
                                    Toast.makeText(UserAddCookbookActivity.this, "发布食谱失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                            for(int i = 0; i < steps.size(); i++) {
                                String step = steps.get(i);

                                //插入食谱步骤信息
                                cookbookStepResult = CookbookStepDao.addCookbookStep(cookbookId, step);
                                if(cookbookStepResult == 0) {
                                    for(int j = 0; j < i; j++) {
                                        //如果插入失败，那么之前插入的要删除
                                        CookbookStepDao.deleteCookbookStep(cookbookId);
                                    }
                                    CookbookFoodDao.deleteCookbookFood(cookbookId);
                                    Toast.makeText(UserAddCookbookActivity.this, "发布食谱失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                            if(cookbookResult == 1) {
                                Toast.makeText(UserAddCookbookActivity.this, "发布食谱成功", Toast.LENGTH_SHORT).show();

                                //存完之后退出该界面并回到主界面
                                finish();
                            }else {
                                Toast.makeText(UserAddCookbookActivity.this, "发布食谱失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            }
        });
    }

    //添加新的食材的输入框
    private void addFoodInputItem() {
        //使用LayoutInflater来加载输入框的布局
        LayoutInflater inflater = LayoutInflater.from(this);
        View itemView = inflater.inflate(R.layout.itemview_food_input_layout, foodInputLayout, false);

        EditText foodName = itemView.findViewById(R.id.itemview_food_input_layout_food_name);
        EditText foodCount = itemView.findViewById(R.id.itemview_food_input_layout_food_count);
        ImageButton addButton = itemView.findViewById(R.id.itemview_food_input_layout_add_food);
        ImageButton deleteButton = itemView.findViewById(R.id.itemview_food_input_layout_delete_food);

        //设置加号按钮点击事件
        addButton.setOnClickListener(view -> addFoodInputItem());

        //设置删除按钮点击事件
        deleteButton.setOnClickListener(view -> {
            foodInputLayout.removeView(itemView);
        });

        //添加到布局中
        foodInputLayout.addView(itemView);
        foodInputLayout.requestLayout();
    }

    //添加新的制作步骤的输入框
    private void addStepInputItem() {
        //使用LayoutInflater来加载输入框的布局
        LayoutInflater inflater = LayoutInflater.from(this);
        View itemView = inflater.inflate(R.layout.itemview_step_input_layout, cookbookStepInputLayout, false);

        EditText step = itemView.findViewById(R.id.itemview_step_input_layout_step);
        ImageButton addButton = itemView.findViewById(R.id.itemview_step_input_layout_add_step);
        ImageButton deleteButton = itemView.findViewById(R.id.itemview_step_input_layout_delete_step);

        //设置加号按钮时间
        addButton.setOnClickListener(view -> addStepInputItem());

        //设置删除按钮点击事件
        deleteButton.setOnClickListener(view -> {
            cookbookStepInputLayout.removeView(itemView);
        });

        //添加到布局中
        cookbookStepInputLayout.addView(itemView);
        cookbookStepInputLayout.requestLayout();
    }

    private void openGallery(View v) {
        //打开文件选择器
        getContentLaucher.launch("image/*");
    }
}